package DB;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

public class DBConnection
{
	private static final String url = "jdbc:jtds:sqlserver://iistest.noea.dk:1433/";
	private static final String userName = "dm67_2";
	private static final String password = "maagodt";
	private DatabaseMetaData dma;
	private static Connection con;
	private static DBConnection instance = null;

	/**
	 * Opretter forbinelsen til databasen
	 */
	private DBConnection()
	{
    	try
		{
			//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			Class.forName("net.sourceforge.jtds.jdbc.Driver");
		}
		catch(Exception e)
		{
			System.out.println("Can not find the driver: "+e.getMessage());
		}

		try
		{
			con = DriverManager.getConnection(url, userName, password);
			con.setAutoCommit(true);
			dma = con.getMetaData();
			System.out.println("Connection to " + dma.getURL());
			System.out.println("Driver " + dma.getDriverName());
			System.out.println("Database product name " + dma.getDatabaseProductName());
		}
		catch(Exception e){
			System.out.println("Problems with the connection to the database: "+e.getMessage());
		}
	}

	/**
	 * Afbryder forbinelsen til databasen
	 */
	public static void closeConnection()
	{
		try
		{
			con.close();
			System.out.println("The connection is closed");
		}
		catch (Exception e){
			System.out.println("Error trying to close the database: "+e.getMessage());
		}
	}

	/**
	 * Returnerer forbindelsesobjektet
	 * @return Forbindelsesobjektet
	 */
	public Connection getDBcon()
	{
		return con;
	}

	/**
	 * Henter instansen af DBConnection (singleton)
	 * @return En instansen af DBConnection
	 */
	public static DBConnection getInstance()
	{
		if (instance == null)
		{
			instance = new DBConnection();
		}
		return instance;
	}
}
